package com.sxbbc.common.core.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.function.common.GetRest;
import com.function.common.RestResponse;
import com.sxbbc.common.basics.exceptions.ThrowJsonException;
import com.sxbbc.common.basics.utils.calculation.CalcuUtils;
import com.sxbbc.common.core.entity.jz.CCustomer;
import com.sxbbc.common.core.entity.jz.OpinionInfo;
import com.sxbbc.common.core.mapper.jz.CCustomerMapper;
import com.sxbbc.common.core.mapper.jz.OpinionInfosMapper;
import com.sxbbc.common.core.service.IOpinionInfosService;
import com.sxbbc.common.core.utils.BasePage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 用户意见表 服务实现类
 * </p>
 *
 * @author leehao
 * @since 2019-05-07
 */
@Service
public class OpinionInfosServiceImpl extends ServiceImpl<OpinionInfosMapper, OpinionInfo> implements IOpinionInfosService {

    @Autowired
    private CCustomerMapper customerMapper;

    /** 默认状态 */
    private static final Integer DEFAULT_STATUS = 0;

    @Override
    public Page<OpinionInfo> queryOpinionList(BasePage<OpinionInfo> page, OpinionInfo opinion) {
        QueryWrapper<OpinionInfo> wrapper = new QueryWrapper<>();
        if (!CalcuUtils.getInstance().isEquals(opinion.getStatus(),DEFAULT_STATUS) && opinion.getStatus() != null) {
            wrapper.eq("status", opinion.getStatus());
        }
        if (page.isPaging()) {
            super.page(page, wrapper);
        } else {
            List<OpinionInfo> list = super.list(wrapper);
            page.setRecords(list);
        }
        for (OpinionInfo o : page.getRecords()) {
            if (o.getCid() != null) {
                CCustomer customer = customerMapper.selectById(o.getCid());
                o.setCname(customer.getNickName());
                o.setCphone(customer.getPhone());
            }
        }
        return page;
    }

    @Override
    public RestResponse handleOpinionStatus(Integer id, Integer status) {
        OpinionInfo opinion = super.getById(id);
        if (opinion == null) {
            return GetRest.getFail("意见被删除或已处理");
        }
        opinion.setStatus(status);
        opinion.setEndTime(new Date());
        boolean save = super.updateById(opinion);
        if (!save) {
            throw new ThrowJsonException("处理意见失败");
        }
        return GetRest.getSuccess("处理成功");
    }
}
